#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QThread>
#include <QMessageBox>
#include <QFile>
#include <QFileDialog>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    main_btnStartSta = true;
    main_state = true;
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::init()
{
    ui->lb_vedio->setScaledContents(main_state);
    this->setWindowTitle("Camera Client");
    this->setWindowFlags(this->windowFlags()&~(Qt::WindowMaximizeButtonHint|Qt::WindowCloseButtonHint));
}

void MainWindow::on_btn_start_clicked()
{
    QString name;

    if ((main_btnStartSta = !main_btnStartSta) == false)
    {
        name = "Stop";
        getPixmap = new GetPixmap;
        thread = new QThread();
        getPixmap->get_ipAddr = main_ipAddr;
        getPixmap->get_port = main_port;

        getPixmap->moveToThread(thread);

        void (GetPixmap:: *sig_getOnePixmap)(QPixmap) = &GetPixmap::get_getOnePixmap;
        void (MainWindow:: *slot_getOnePixmap)(QPixmap) = &MainWindow::main_getOnePixmap;

        connect(getPixmap,sig_getOnePixmap,this,slot_getOnePixmap);
        thread->start();
        connect(thread,&QThread::started,getPixmap,&GetPixmap::run);
    }
    else
    {
        name = "Start";
        thread->exit();
        disconnect(getPixmap,SIGNAL(get_getOnePixmap(QPixmap)),this,NULL);
        delete  getPixmap;
    }

    ui->btn_start->setText(name);
}

void MainWindow::on_btn_screenshot_clicked()
{
    save_pix = show_pix;

    if (save_pix.isNull())
    {
        QMessageBox::information(this,tr("Info"),tr("There are no images to save."));
    }
    else
    {
        QString fileName = QFileDialog::getSaveFileName(this,tr("Save File"),QDir::homePath(),tr("jpegfile(*.jpg)"));

        if (fileName.isEmpty())
        {
            QMessageBox::information(this,"Infor",tr("Save Cancel"));
            return;
        }

        save_pix.save(fileName);
    }
}


void MainWindow::on_btn_quit_clicked()
{
    this->close();
}


void MainWindow::main_getOnePixmap(QPixmap pix)
{
    show_pix = pix;

    ui->lb_vedio->setPixmap(show_pix);
    ui->lb_vedio->show();
}
